import Vue from 'vue'
import {
  ACCESS_TOKEN,
  USER_INFO,
  UI_CACHE_DB_DICT_DATA
} from '@/store/mutation-types'
// function filterModuleRouters (routers) {
//   return fixRootPath(
//     routers.filter(
//       router => router.name.startsWith('New') && router.name !== 'HomeDef'
//     )
//   )
// }

function getUserInfo (params) {
  return window.$get(window.$api.upms.upms.info, params)
}

function getMenu (params) {
  return window.$get(window.$api.upms.upms.getRouters, params)
}

function getDictData (params) {
  return window.$get(window.$api.upms.upms.getDict, params)
}

function login (params) {
  return window.$postType(window.$api.upms.upms.login, params)
}

function logout (params) {
  return window.$post(window.$api.upms.upms.logout, params)
}
// function fixRootPath (routers) {
//   for (const router of routers) {
//     // let path = ''
//     if (!router.redirect || router.redirect === 'noRedirect') {
//       // let smenu = JSON.parse(JSON.stringify(router))
//       // while (smenu) {
//       //   path += '/' + smenu.path.replace(/^\/*/g, '')
//       //   if (!smenu.children || !smenu.children.length) break;
//       //   smenu = smenu.children[0]
//       // }
//       router.redirect = '/homeDef'
//     }
//     router.component = 'layouts/RouteView'
//   }
//   return routers
// }

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    welcome: '',
    permissionList: [],
    roleList: [],
    menuList: [],
    info: {},
    dictList: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_ROLELIST: (state, roleList) => {
      state.roleList = roleList
    },
    SET_MENULIST: (state, menuList) => {
      state.menuList = menuList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_DICTLIST: (state, dictList) => {
      state.dictList = dictList
    }
  },
  actions: {
    // 登录
    Login ({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            if (window.isSuccess(response)) {
              const data = response.data
              commit('SET_TOKEN', data)
              Vue.ls.set(ACCESS_TOKEN, data, 24 * 60 * 60 * 1000)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetUserInfo ({
      commit,
      params
    }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then(response => {
            if (!window.isSuccess(response)) {
              reject(response.message || '请求异常')
            }
            const permissionData = response.data.permissions
            const rolesData = response.data.user.role
            const userData = response.data.user
            if (window._UTILS.isArray(permissionData)) {
              commit('SET_PERMISSIONLIST', permissionData)
            } else {
              reject(new Error('GetUserInfo: permissions must be a non-null array !'))
            }

            if (window._UTILS.isObject(rolesData) && rolesData != null) {
              const rolesList = [rolesData]
              commit('SET_ROLELIST', rolesList)
            } else {
              reject(new Error('GetUserInfo: role must be a non-null !'))
            }

            if (window._UTILS.isObject(userData) && !window._UTILS.isEmptyObject(userData)) {
              Vue.ls.set(USER_INFO, userData, 24 * 60 * 60 * 1000)
              commit('SET_INFO', userData)
            } else {
              reject(new Error('GetUserInfo: user must be a non-null Object!'))
            }

            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 字典值
    GetDictData ({
      commit,
      params
    }) {
      return new Promise((resolve, reject) => {
        getDictData()
          .then(response => {
            console.log('获取字典值')
            if (!window.isSuccess(response)) {
              reject(response.message || '请求异常')
            }
            const datas = response.data
            let dictList = {}
            for (const key in datas) {
              let data = datas[key]
              data.sort((a, b) => {
                return a.sortNo - b.sortNo
              })
              data = data.map(item => {
                return {
                  label: item.name,
                  value: item.value,
                  children: item.children
                }
              })
              dictList[key] = data
            }
            console.log('dictList',dictList)
            commit('SET_DICTLIST', dictList)
            resolve(dictList)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户菜单
    GetMenu ({
      commit,
      params
    }) {
      return new Promise((resolve, reject) => {
        getMenu()
          .then(response => {
            console.log('获取用户菜单')
            let menuData = (response.data = response.data || []) // filterModuleRouters(response.data || []) || []
            if (window._UTILS.isArray(menuData) && menuData.length) {
              menuData.forEach((item, index) => {
                if (item['children'] && item['type'] === '1') {
                  let hasChildrenMenu = item['children'].filter(i => {
                    return !i.hidden
                  })
                  if (hasChildrenMenu == null || !hasChildrenMenu.length) {
                    item['hidden'] = true
                  }
                }
              })
              commit('SET_MENULIST', menuData)
            } else {
              // reject(new Error('queryMenus: data must be a non-null array !'))
              reject(new Error('该用户没有分配菜单权限!'))
            }
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    Logout ({
      commit,
      state
    }) {
      return new Promise(resolve => {
        logout()
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_PERMISSIONLIST', [])
            commit('SET_MENULIST', [])
            commit('SET_ROLELIST', [])
            commit('SET_INFO', {})
            Vue.ls.remove(ACCESS_TOKEN)
            Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    }
  }
}

export default user
